// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.XmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.mapper.KdlPurchaseinBMapper;
import com.javaweb.admin.service.INcServiceLogService;
import com.javaweb.admin.vo.kdlpurchasein.KdlPurchaseinListVo;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.mapper.KdlPurchaseinMapper;
import com.javaweb.admin.query.KdlPurchaseinQuery;
import com.javaweb.admin.service.IKdlPurchaseinService;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.admin.vo.kdlpurchasein.KdlPurchaseinInfoVo;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import com.javaweb.system.constant.Constants;
import com.javaweb.system.utils.ShiroUtils;
import com.seegw.shaphar.DDKJConfig;
import com.seegw.shaphar.KDLConfig;
import com.seegw.shaphar.KDLRequest;
import com.sphsine.bip.SHYPConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.Serializable;
import java.util.*;

/**
  * <p>
  * 采购质检订单回传 服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2024-01-24
  */
@Service
public class KdlPurchaseinServiceImpl extends BaseServiceImpl<KdlPurchaseinMapper, KdlPurchasein> implements IKdlPurchaseinService {

    @Autowired
    private KdlPurchaseinMapper kdlPurchaseinMapper;

    @Autowired
    private KdlPurchaseinBMapper kdlPurchaseinBMapper;

    @Autowired
    INcServiceLogService ncServiceLogService;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getList(BaseQuery query) {
        KdlPurchaseinQuery kdlPurchaseinQuery = (KdlPurchaseinQuery) query;
        // 查询条件
        QueryWrapper<KdlPurchasein> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");
        if(!StringUtils.isEmpty(kdlPurchaseinQuery.getVendorpo())){
            queryWrapper.like("vendorpo",kdlPurchaseinQuery.getVendorpo());
        }
        if(!StringUtils.isEmpty(kdlPurchaseinQuery.getCahpo())){
            queryWrapper.like("cahpo",kdlPurchaseinQuery.getCahpo());
        }
        if(!StringUtils.isEmpty(kdlPurchaseinQuery.getRiqiBegin())){
            queryWrapper.gt("grdate",kdlPurchaseinQuery.getRiqiBegin());
        }
        if(!StringUtils.isEmpty(kdlPurchaseinQuery.getRiqiEnd())){
            queryWrapper.lt("grdate",kdlPurchaseinQuery.getRiqiEnd());
        }


        // 获取数据列表
        IPage<KdlPurchasein> page = new Page<>(kdlPurchaseinQuery.getPage(), kdlPurchaseinQuery.getLimit());
        IPage<KdlPurchasein> pageData = kdlPurchaseinMapper.selectPage(page, queryWrapper);
//        pageData.convert(x -> {
//            KdlPurchaseinListVo kdlPurchaseinListVo = Convert.convert(KdlPurchaseinListVo.class, x);
//            return kdlPurchaseinListVo;
//        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public Object getInfo(Serializable id) {
        KdlPurchasein entity = (KdlPurchasein) super.getInfo(id);
        // 返回视图Vo
        KdlPurchaseinInfoVo kdlPurchaseinInfoVo = new KdlPurchaseinInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, kdlPurchaseinInfoVo);
        return kdlPurchaseinInfoVo;
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult create(KdlPurchaseinDto dto) {
        try {
            KdlPurchasein entity = dto.getPurchasein();
            KdlPurchaseinB[] purchaseinLines = dto.getPurchaseinLines();
            kdlPurchaseinMapper.insert(entity);
            for (KdlPurchaseinB detail : purchaseinLines) {
                detail.setPid(entity.getId());
                kdlPurchaseinBMapper.insert(detail);
            }
            return JsonResult.success();
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult update(KdlPurchaseinDto dto) {
        try {
            KdlPurchasein entity = dto.getPurchasein();
            KdlPurchaseinB[] purchaseinLines = dto.getPurchaseinLines();
            kdlPurchaseinMapper.insert(entity);
            //删除之前的明细
            Map<String,Object> param = new HashMap<>();
            param.put("pid",entity.getId());
            kdlPurchaseinBMapper.deleteByMap(param);
            for (KdlPurchaseinB detail : purchaseinLines) {
                detail.setPid(entity.getId());
                kdlPurchaseinBMapper.insert(detail);
            }
            return JsonResult.success();
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getMaxSyncTime() {
        return kdlPurchaseinMapper.GetMaxSyncTime();
    }

    /*
    * 获取康德乐采购质检订单回传数据
    */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncPurchase(KdlPurchaseinQuery query) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<CAH3PL>");
        sb.append("<Head>");
        sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
        sb.append("<DocType>Z01-KDL</DocType>");
        sb.append("<StartTime>" + query.getStarttime() + "</StartTime>");
        sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
        sb.append("</Head>");
        sb.append("</CAH3PL>");
        NcServiceLog log = new NcServiceLog();
        //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
        String body = sb.toString();
        log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());
        log.setRequestBody(body);
        log.setSubmitTime(DateUtils.now());
        try {
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            StringBuilder sbResult = new StringBuilder();
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                log.setResponseBody(result);
                log.setResponseCode("");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlPurchaseinDto dto = new KdlPurchaseinDto();
                        KdlPurchasein purchasein = new KdlPurchasein();
                        KdlPurchaseinB purchaseinB = new KdlPurchaseinB();
                        purchasein.setPrincipalid(CommonUtils.XmlGetNodeContent(headResult, "PrincipalID"));
                        purchasein.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                        purchasein.setVendorpo(CommonUtils.XmlGetNodeContent(headResult, "VendorPO"));
                        purchasein.setDoctype(CommonUtils.XmlGetNodeContent(headResult, "DocType"));
                        String grdate = CommonUtils.XmlGetNodeContent(headResult, "GRDate");
                        purchasein.setGrdate(grdate);
                        purchasein.setCahpo(CommonUtils.XmlGetNodeContent(headResult, "CAHPO"));
                        purchasein.setVendorcode(CommonUtils.XmlGetNodeContent(headResult, "VendorName"));
                        purchasein.setCompanycode(CommonUtils.XmlGetNodeContent(headResult, "CompanyCode"));
                        List<KdlPurchasein> list = kdlPurchaseinMapper.selectList(new QueryWrapper<KdlPurchasein>().eq("vendorpo", purchasein.getVendorpo()));

                        if (list.size() == 0) {
                            kdlPurchaseinMapper.insert(purchasein);
                        } else {
                            purchasein.setUpdateTime(DateUtils.now());
                            purchasein.setId(list.get(0).getId());
                            kdlPurchaseinMapper.updateById(purchasein);
                        }
                        //遍历明细Details
                        Element detail = null;
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            purchaseinB.setPid(purchasein.getId());
                            purchaseinB.setSn(CommonUtils.XmlGetNodeContent(detail, "SN"));
                            purchaseinB.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            purchaseinB.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            purchaseinB.setCanpolineno(CommonUtils.XmlGetNodeContent(detail, "CANPOLineNO"));
                            purchaseinB.setInspectionlot(CommonUtils.XmlGetNodeContent(detail, "InspectionLot"));
                            purchaseinB.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            purchaseinB.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            purchaseinB.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            purchaseinB.setComdescription(CommonUtils.XmlGetNodeContent(detail, "ComDescription"));
                            purchaseinB.setMaterialspec(CommonUtils.XmlGetNodeContent(detail, "MaterialSpec"));
                            purchaseinB.setMaterialform(CommonUtils.XmlGetNodeContent(detail, "MaterialForm"));
                            purchaseinB.setRegistno(CommonUtils.XmlGetNodeContent(detail, "RegistNo"));
                            purchaseinB.setProductgroupcode(CommonUtils.XmlGetNodeContent(detail, "ProductGroupCode"));
                            purchaseinB.setProductgroupdes(CommonUtils.XmlGetNodeContent(detail, "ProductGroupDes"));
                            purchaseinB.setGspcategorycode(CommonUtils.XmlGetNodeContent(detail, "GSPCategoryCode"));
                            purchaseinB.setGspcategorydes(CommonUtils.XmlGetNodeContent(detail, "GSPCategoryDes"));
                            purchaseinB.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            purchaseinB.setSerialno(CommonUtils.XmlGetNodeContent(detail, "SerialNo"));
                            purchaseinB.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            purchaseinB.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            purchaseinB.setManufacturername(CommonUtils.XmlGetNodeContent(detail, "ManufacturerName"));
                            purchaseinB.setSubmaufacturername(CommonUtils.XmlGetNodeContent(detail, "SubMaufacturerName"));
                            purchaseinB.setGrquantity(CommonUtils.XmlGetNodeContent(detail, "GRQuantity", 0));
                            purchaseinB.setCahuom(CommonUtils.XmlGetNodeContent(detail, "CAHUOM"));
                            purchaseinB.setVendoruom(CommonUtils.XmlGetNodeContent(detail, "VendorUOM"));
                            purchaseinB.setGrplant(CommonUtils.XmlGetNodeContent(detail, "GRPlant"));
                            purchaseinB.setVendorplant(CommonUtils.XmlGetNodeContent(detail, "VendorPlant"));
                            purchaseinB.setGrconclusion(CommonUtils.XmlGetNodeContent(detail, "GRConclusion"));
                            purchaseinB.setQapassqty(CommonUtils.XmlGetNodeContent(detail, "QAPassQty", 0));
                            purchaseinB.setInspectionresult(CommonUtils.XmlGetNodeContent(detail, "InspectionResult"));
                            purchaseinB.setQarejectqty(CommonUtils.XmlGetNodeContent(detail, "QARejectQty", 0));
                            purchaseinB.setRejectresult(CommonUtils.XmlGetNodeContent(detail, "RejectResult"));
                            purchaseinB.setTreatmentforreject(CommonUtils.XmlGetNodeContent(detail, "TreatmentforReject"));
                            purchaseinB.setInspectionidname1(CommonUtils.XmlGetNodeContent(detail, "InspectionIDName1"));
                            purchaseinB.setInspectiondate1(CommonUtils.XmlGetNodeContent(detail, "InspectionDate1"));
                            purchaseinB.setInspectionidname2(CommonUtils.XmlGetNodeContent(detail, "InspectionIDName2"));
                            purchaseinB.setInspectiondate2(CommonUtils.XmlGetNodeContent(detail, "InspectionDate2"));
                            purchaseinB.setQuarantineqty(CommonUtils.XmlGetNodeContent(detail, "QuarantineQty", 0));
                            purchaseinB.setQuarantineresult(CommonUtils.XmlGetNodeContent(detail, "QuarantineResult"));
                            purchaseinB.setSampleqty(CommonUtils.XmlGetNodeContent(detail, "SampleQty", 0));
                            purchaseinB.setSamplelocation1010(CommonUtils.XmlGetNodeContent(detail, "SampleLocation1010", 0));
                            purchaseinB.setSamplelocation1005(CommonUtils.XmlGetNodeContent(detail, "SampleLocation1005", 0));
                            purchaseinB.setUdconclusion(CommonUtils.XmlGetNodeContent(detail, "UDConclusion"));
                            purchaseinB.setCarrier(CommonUtils.XmlGetNodeContent(detail, "Carrier"));
                            purchaseinB.setCarriermethod(CommonUtils.XmlGetNodeContent(detail, "CarrierMethod"));
                            purchaseinB.setTransitdate(CommonUtils.XmlGetNodeContent(detail, "TransitDate"));
                            purchaseinB.setTransittime(CommonUtils.XmlGetNodeContent(detail, "TransitTime"));
                            purchaseinB.setArrivaltemperature(CommonUtils.XmlGetNodeContent(detail, "ArrivalTemperature"));
                            purchaseinB.setTransitmethod(CommonUtils.XmlGetNodeContent(detail, "TransitMethod"));
                            purchaseinB.setDespatchtime(CommonUtils.XmlGetNodeContent(detail, "DespatchTime"));
                            purchaseinB.setMethodoftemperature(CommonUtils.XmlGetNodeContent(detail, "MethodofTemperature"));
                            purchaseinB.setStockarrivetime(CommonUtils.XmlGetNodeContent(detail, "StockArriveTime"));
                            purchaseinB.setPlaceofdelivery(CommonUtils.XmlGetNodeContent(detail, "PlaceofDelivery"));
                            purchaseinB.setTemperatureofstock(CommonUtils.XmlGetNodeContent(detail, "TemperatureofStock"));
                            purchaseinB.setInventorypacking(CommonUtils.XmlGetNodeContent(detail, "InventoryPacking"));
                            purchaseinB.setWofdareport(CommonUtils.XmlGetNodeContent(detail, "WOFDAReport"));
                            purchaseinB.setWodeliverynote(CommonUtils.XmlGetNodeContent(detail, "WODeliveryNote"));
                            purchaseinB.setDeliverier(CommonUtils.XmlGetNodeContent(detail, "Deliverier"));
                            purchaseinB.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));
                            purchaseinB.setSapbatch(CommonUtils.XmlGetNodeContent(detail, "SAPbatch"));


                            List<KdlPurchaseinB> list1 = kdlPurchaseinBMapper.selectList(new QueryWrapper<KdlPurchaseinB>().eq("sn", purchaseinB.getSn()).eq("inspectionlot",purchaseinB.getInspectionlot()));
                            if (list1.size() == 0) {
                                kdlPurchaseinBMapper.insert(purchaseinB);
                            } else {
                                purchaseinB.setId(list1.get(0).getId());
                                purchaseinB.setUpdateTime(DateUtils.now());
                                kdlPurchaseinBMapper.updateById(purchaseinB);
                            }
                        }

                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(StringUtils.trim(ex.getMessage()));
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            log.setResponseBody(StringUtils.trim(ex.getMessage()));
            log.setResponseCode("500");
            log.setResponseResult("");
            ncServiceLogService.save(log);
            return JsonResult.error(ex.getMessage());
        }
    }

    /*
     * 获取康德乐采购质检明细数据
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getPurchaseinInspectionResult(Integer pid) {
        return JsonResult.success(kdlPurchaseinMapper.getPurchaseinInspectionResult(pid));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getPurchaseinList(BaseQuery query) {
        KdlPurchaseinQuery kdlPurchaseinQuery = (KdlPurchaseinQuery) query;
        // 获取数据列表
        kdlPurchaseinQuery.setOrglist(ShiroUtils.getOrgCode());
        IPage<KdlPurchasein> page = new Page<>(kdlPurchaseinQuery.getPage(), kdlPurchaseinQuery.getLimit());
        IPage<KdlPurchasein> pageData = kdlPurchaseinMapper.getPurchaseinList(page, kdlPurchaseinQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult exportPurchaseinList(BaseQuery query) {
        KdlPurchaseinQuery kdlPurchaseinQuery = (KdlPurchaseinQuery) query;
        // 获取数据列表
        kdlPurchaseinQuery.setPage(1);
        kdlPurchaseinQuery.setLimit(-1);
        kdlPurchaseinQuery.setOrglist(ShiroUtils.getOrgCode());
        IPage<KdlPurchaseinListVo> page = new Page<>(kdlPurchaseinQuery.getPage(), kdlPurchaseinQuery.getLimit());
        IPage<KdlPurchaseinListVo> pageData = kdlPurchaseinMapper.getExportPurchaseinList(page, kdlPurchaseinQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<PurchaseinInspectionResult> getPurchaseSubmitList() {
        return kdlPurchaseinMapper.getPurchaseSubmitList();
    }

    @Override
    public void updateSubmitNCStatus(Integer id, String status) {

    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String GetMaxSyncTime() {
        return kdlPurchaseinMapper.GetMaxSyncTime();
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult edit(KdlPurchasein entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult delete(KdlPurchasein entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

}